<?php

namespace App\Admin\Controllers;

use App\Models\Department;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Tree;
use Dcat\Admin\Http\Controllers\AdminController;
use function PHPUnit\Framework\isEmpty;

class DepartmentController extends AdminController
{

    public function index(Content $content)
    {
        return $content->header('部门管理')
            ->body(function (Row $row) {
                $tree = new Tree(new Department());
                $tree->maxDepth(3);//限制最大层级数
                $tree->expand();//展开子节点数据#
                $tree->branch(function ($branch) {
//                    $src = config('admin.upload.host') . '/' . $branch['logo'] ;
//                    $logo = "<img src='$src' style='max-width:30px;max-height:30px' class='img'/>";

                    return "{$branch['id']} - {$branch['name']} ";
                });
//                $tree->actions(function (Tree\Actions $actions) {
//                    if ($actions->row->id ==1) {
//                        $actions->disableDelete(); // 禁用删除按钮
//                    }
//
//                    // 添加新的action
//                    $actions->append('添加', function ($id) {
//                        return "<a href='/admin/departments/create?pid={$id}' class='btn btn-sm btn-primary'>添加</a>";
//                    });
//                });
                $row->column(6, $tree);
                $row->column(6, $this->grid());
            });
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Department(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('pid')->display(function ($pid){
                if($pid==0){
                    return '系统';
                }else{
                    return Department::query()->where('id',$pid)->value('name');
                }
            });
            $grid->column('name');
            $grid->column('principal_id')->display(function ($principal_id){
                if($principal_id==0){
                    return '无';
                }else{
                    return User::query()->where('id',$principal_id)->value('username');
                }
            });
            $grid->column('sort');
            $grid->column('status')->switch();
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Department(), function (Show $show) {
            $show->field('id');
            $show->field('pid');
            $show->field('name');
            $show->field('principal_id');
            $show->field('sort');
            $show->field('status');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Department(), function (Form $form) {
            $form->display('id');
            $form->select('pid')->options(function () {
                try {
                    // 尝试获取所有部门，pluck直接从数据库提取必要信息，减少内存占用
                    $deps = Department::pluck('name', 'id');
                } catch (\Exception $e) {
                    // 根据业务需求，可以选择抛出异常或者返回默认值
                    return ['系统' => 0];
                }

                // 检查是否有部门被获取
                if ($deps->isEmpty()) {
                    // 如果没有部门，则仅返回“系统”选项
                    return ['系统' => 0];
                } else {
                    // 将"系统"选项添加到部门列表的前面
                    $deps->prepend('系统', 0);
                    return $deps->all(); // 使用all()转换为数组
                }
            })->default(0);
            $form->text('name');
            $form->select('principal_id')->options(User::all()->pluck('username', 'id'));
            $form->number('sort')->default(0);
            $form->radio('status')->options([1 => '正常', 0 => '禁用'])->default(1);
        })->saving(function (Form $form) {
            if ($form->isEditing()) {
                if((int)($form->status)!=$form->model()->status && (int)($form->status)==0){
                    $allstu=Department::query()->where('pid',$form->model()->id)->exists();
                    if($allstu){
                        return $form->response()->error('禁用失败，请先禁用子部门')->refresh();
                    }
                };
            }
        });
    }
}
